package com.ericsson.rm.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ericsson.rm.util.Utility;
 
@Aspect
public class LoggingAspect {
	
	private static Logger logger = null; 
	
	@Before("execution(* com.ericsson.rm.controller.CustomerController.p*(..)) || execution(* com.ericsson.rm.controller.*.i*(..)) || execution(* com.ericsson.rm.controller.*.g*(..))")
	public void logBefore(JoinPoint joinPoint) {
 
		System.out.println("logBefore() is running!");
		System.out.println("hijacked : " + joinPoint.getSignature().getName());
		System.out.println("******");
	}
	
	@After("execution(* com.ericsson.rm.controller.CustomerController.p*(..)) || execution(* com.ericsson.rm.controller.*.i*(..)) || execution(* com.ericsson.rm.controller.*.g*(..))")
	public void logAfter(JoinPoint joinPoint) {
 
		System.out.println("logAfter() is running!");
		System.out.println("hijacked : " + joinPoint.getSignature().getName());
		System.out.println("******");
	}
	
	@Around("execution(* com.ericsson.rm.controller.CustomerController.p*(..)) || execution(* com.ericsson.rm.controller.*.i*(..)) || execution(* com.ericsson.rm.controller.*.g*(..))")
	public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
		
		logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
		
		if(logger.isDebugEnabled()){
			logger.debug(joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName()+"() entering...");		
		}
		System.out.println(joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName()+"() entering...");
		
		joinPoint.proceed(); //continue on the intercepted method
		
		if(logger.isDebugEnabled()){
			logger.debug(joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName()+"() exiting...");		
		}
		System.out.println(joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName()+"() exiting...");
	}
	
	@AfterThrowing("execution(* com.ericsson.rm.controller.*.*(..)) || execution(* com.ericsson.rm.service.*.*(..)) || execution(* com.ericsson.rm.validator.*.*(..))")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
		
		logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
		
		logger.error(joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName()+"() Throwing exception: "+Utility.getStackTrace(error));	
	
		System.out.println("logAfterThrowing() is running!");
		System.out.println(joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName()+"() Throwing exception: "+Utility.getStackTrace(error));
    }
}
